package com.example.reagent_management.ui.activity

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import androidx.work.await
import com.example.lib_base.base.BaseActivity
import com.example.lib_base.event.ShareViewModel
import com.example.lib_base.utils.DateConvertUtils
import com.example.lib_base.utils.MMKVUtils
import com.example.reagent_management.R
import com.example.reagent_management.service.StateService
import com.example.reagent_management.service.works.*
import com.example.reagent_management.ui.setting.*
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
import javax.inject.Inject

@AndroidEntryPoint
class MainActivityKt : BaseActivity() {

    private lateinit var mEvent: ShareViewModel
    private val mState: MainActivityModel by viewModels()

    @Inject
    lateinit var works: WorksBuild

    override fun getLayoutResId(): Int {
        return R.layout.activity_main
    }

    override fun initViewModel() {
        mEvent = getApplicationScopeViewModel(ShareViewModel::class.java)
    }

    private lateinit var connection: ServiceConnection

    override fun initViewOrObserve() {
        //绑定服务 温湿度提醒
        val intent = Intent(this, StateService::class.java)
        connection = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName, service: IBinder) {
                (service as StateService.StateBinder).service.states.observe(this@MainActivityKt
                ) {
                    val tem1 = MMKVUtils.getHelper().decodeDouble(TEMP1_REMIND, 25.0)
                    val tem2 = MMKVUtils.getHelper().decodeDouble(TEMP2_REMIND, 28.0)
                    mEvent.setHumidity(it.humidity)
                    mEvent.setTemp(it.temp)
                    if (tem1 != 0.0 && tem2 != 0.0) {
                        if (!((it.temp in tem1..tem2) || (it.temp in tem2..tem1))) {
                            //温度不在范围生成消息通知
                            setWorkRemind(this@MainActivityKt, mEvent, works.manager, {
                                works.Builder().setInputData(
                                    setMessageData("温度异常:|${it.temp}℃", 0),
                                    MessageWork::class.java
                                ).build(0, "message_work")
                            }, lifecycleScope)
                        }
                    }
                    val hub1 = MMKVUtils.getHelper().decodeDouble(TEMP3_REMIND, 35.0)
                    val hub2 = (MMKVUtils.getHelper().decodeDouble(TEMP4_REMIND, 40.0))
                    if (hub1 != 0.0 && hub2 != 0.0) {
                        if (!((it.humidity in hub1..hub2) || (it.humidity in hub2..hub1))) {
                            //湿度不在范围生成消息通知
                            setWorkRemind(this@MainActivityKt, mEvent, works.manager, {
                                works.Builder().setInputData(
                                    setMessageData("湿度异常:|${it.humidity}%RH", 0),
                                    MessageWork::class.java
                                ).build(0, "message_work")
                            }, lifecycleScope)
                        }
                    }
                }
            }

            override fun onServiceDisconnected(name: ComponentName) {
            }
        }
        bindService(intent, connection, BIND_AUTO_CREATE)

        //开启定期清理工作
        val cleanId = MMKVUtils.getHelper().decodeString("clean_id","00-00-00-00-00")
        lifecycleScope.launch {
            if (works.manager.getWorkInfoById(UUID.fromString(cleanId)).await() == null){
                val uuid = works.Builder().setRepeatWorkTime(31,CleanWork::class.java).build(1,"clean_work")
                MMKVUtils.getHelper().encode("clean_id",uuid.toString())
            }
        }

        //监听返回键事件
        mEvent.isToCloseActivityIfAllowed.observe(this) {
            val navController = Navigation.findNavController(this, R.id.fragmentContainerView)
            if (navController.currentDestination != null && navController.currentDestination!!
                    .id != R.id.mainFragment
            ) {
                navController.navigateUp()
            } else {
                super.onBackPressed()
            }
        }

        //日期、库存提醒  TODO
        var job = mState.setReminds()
        mEvent.hasChangedRemind.observe(this) {
            if (it != null && it) {
//                job.cancelChildren()
                job.cancel()
                if (job.isCancelled) {
                    job = mState.setReminds()
                }
            }
        }
        mState.remindInfoList.observe(this) { list ->
            //到这里数据库发生改变时可随时监听并拿到过滤部分好的数据,但设置那里如果一直变化的话也还要做对比
            val day = MMKVUtils.getHelper().decodeInt(DAY__REMIND, 1)
            val count = MMKVUtils.getHelper().decodeInt(COUNT_REMIND, 1)
            val thisTime = System.currentTimeMillis()
            list.forEach {
                if (it.remindDay >= thisTime && it.remindDay - thisTime <= day * 86400000) {
                    //日期提醒
                    //TODO 要检测是否提醒过  关联出入库和试剂信息表 涉及到杀死应用问题(未解决，默认不主动杀死应用)
                    lifecycleScope.launch(Dispatchers.IO) {
                        val hasRemind = mState.hasRemind(1, it.operateId)
                        Log.e("hasRemind", "initViewOrObserve: $hasRemind")
                        if (!hasRemind) {
                            works.manager.cancelAllWorkByTag("${it.operateId}")
                            setWorkRemind(this@MainActivityKt, works.manager, {
                                works.Builder().setInputData(
                                    setMessageData(
                                        "项目简称-${it.projectName}\n试剂名-${it.reagentName}\n" +
                                                "到期时间-${
                                                    DateConvertUtils.convertTimeToStringCH(
                                                        it.remindDay,
                                                        "yyyy-MM-dd HH:mm:ss"
                                                    )
                                                }\n" +
                                                "剩余天数->|" +
                                                "$day",
                                        1,
                                        it.operateId,
                                        Calendar.getInstance().timeInMillis
                                    ),
                                    MessageWork::class.java
                                ).build("${it.operateId}", it.remindDay - thisTime)
                            }, lifecycleScope)
                        }
                    }
                }
                if (it.remindCount <= count) {
                    //库存提醒
                    lifecycleScope.launch(Dispatchers.IO) {
                        val hasRemind = mState.hasRemind(2, it.operateId)
                        if (!hasRemind) {
                            setWorkRemind(this@MainActivityKt, mEvent, works.manager, {
                                works.Builder().setInputData(
                                    setMessageData(
                                        "项目简称-${it.projectName}\n试剂名-${it.reagentName}\n库存剩余数量:|" +
                                                "${it.remindCount}",
                                        2,
                                        it.operateId
                                    ),
                                    MessageWork::class.java
                                ).build(0, "message_count_work")
                            }, lifecycleScope)
                        }
                    }
                }
            }
        }
    }

    override fun onBackPressed() {
        mEvent.requestToCloseActivityIfAllowed(true)
    }

    override fun onDestroy() {
        unbindService(connection)
        //解决退出程序时不点击查看消息,但还保留在内存的viewModel数据在显示
        mEvent.messageRemind.value = 0
//        works.manager.cancelAllWork()
        super.onDestroy()
    }


    //TODO  lifecycleScope
    // Create a new coroutine in the lifecycleScope　　　
//    viewLifecycleOwner.lifecycleScope.launch {
//        // repeatOnLifecycle launches the block in a new coroutine every time the
//        // lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED.
//        viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
//            // Trigger the flow and start listening for values.
//            // This happens when lifecycle is STARTED and stops
//            // collecting when the lifecycle is STOPPED
//            viewModel.someDataFlow.collect {
//                // Process item
//            }
//        }
//    }

}